package com.springapp.mvc;

import org.jsoup.HttpStatusException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
@RequestMapping("/search")
public class ResultController {
    @RequestMapping(method = RequestMethod.GET)
    public String printWelcome(ModelMap model, @RequestParam String q, @RequestParam int pageStart, @RequestParam(required = false,value = "pageEnd",defaultValue = "0") int pageEnd) throws IOException{
        List results = new ArrayList<Data>();
        int page = pageStart-1;
        String pClass = ".g";
        try
        {
            while(page<pageEnd)
            {
                String searchUrl = "https://www.google.com.vn/search?q=site%3Avi-vn.facebook.com+"
                        +URLEncoder.encode(q,"UTF-8")+"+\""
                        +URLEncoder.encode("lượt thích","UTF-8")
                        +"\"&start="+page+"0";
                Document doc = Jsoup.connect(searchUrl)
                        .userAgent("Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_6; en-US) AppleWebKit/530.5 (KHTML, like Gecko) Chrome/ Safari/530.5")
                        .get();
                if (doc.select(pClass).size()==0) break;
                for(int i =0;i<doc.select(pClass).size();++i)
                {
                    String title = doc.select(pClass).get(i).select(".r").text();
                    String url = doc.select(pClass).get(i).select(".r a").eq(0).attr("href");

                    if(url.indexOf("https://vi-vn.facebook.com/notes/")!=-1
                            ||url.indexOf("https://vi-vn.facebook.com/help/")!=-1
                            ||url.indexOf("https://vi-vn.facebook.com/events/")!=-1
                            ||url.indexOf("https://vi-vn.facebook.com/public/")!=-1
                            ||url.indexOf("https://vi-vn.facebook.com/media/")!=-1
                            ||url.indexOf("https://vi-vn.facebook.com/note.php")!=-1
                            ||url.indexOf("http://vi-vn.facebook.com/notes/")!=-1
                            ||url.indexOf("http://vi-vn.facebook.com/help/")!=-1
                            ||url.indexOf("http://vi-vn.facebook.com/events/")!=-1
                            ||url.indexOf("http://vi-vn.facebook.com/public/")!=-1
                            ||url.indexOf("http://vi-vn.facebook.com/media/")!=-1
                            ||url.indexOf("http://vi-vn.facebook.com/note.php")!=-1)
                        continue;
                    Matcher m;

                    if(url.indexOf("https://vi-vn.facebook.com/pages/")!=-1)
                    {
                        m = Pattern.compile("https://vi-vn.facebook.com/pages/[^/]+/[^/?#%&]+").matcher(url);
                        m.find();
                        url = m.group();
                    }
                    else if(url.indexOf("https://vi-vn.facebook.com/")!=-1)
                    {
                        m = Pattern.compile("https://vi-vn.facebook.com/[^/?#%&]+").matcher(url);
                        m.find();
                        url = m.group();
                    }
                    url = url.replace("vi-vn","www");

                    m = Pattern.compile("\\s[0-9.]+\\slượt\\sthích").matcher( doc.select(pClass).get(i).text());
                    int likeNum = 0;
                    try {
                        if (m.find())
                            likeNum = Integer.parseInt(m.group().replace("lượt thích", "").replace(".", "").replace(" ", ""));
                    }
                    catch (NumberFormatException e)
                    {
                        System.out.print("NumberFormatException");
                    }

                    Data temp = new Data(title,url,likeNum);
                    for(int j=0;j<results.size();++j)
                    {
                        if (temp.getUrl().equals(((Data)results.get(j)).getUrl()))
                            if(temp.getLikeNum()>((Data)results.get(j)).getLikeNum())
                            {
                                results.set(j,temp);
                                break;
                            }
                            else break;


                        if (temp.getLikeNum()>=((Data)results.get(j)).getLikeNum())
                        {
                            results.add(j,temp);
                            break;
                        }
                        if (j==results.size()-1)
                        {
                            results.add(temp);
                            break;
                        }
                    }
                    if (results.size()==0) results.add(temp);
                }
                ++page;
                Thread.sleep(5000);
            }
        }
        catch (Exception e)
        {
            model.addAttribute("error", e.getMessage());

        }

        model.addAttribute("results",results);
        model.addAttribute("count",results.size());
        model.addAttribute("req",q);
        return "search";
    }
}